package com.example.shipload_e;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.example.shipload_e.update_tool.NetworkUtil;
import com.example.shipload_e.update_tool.Tools;
import com.example.shipload_e.update_tool.UpdateBiz;
import com.example.shipload_e.update_tool.VersionEntity;
import com.example.shipload_e.util.HttpConstant;

public class ShipMentWelcomeActivity extends Activity {
	private ImageButton	                  idTitleLeftBtn;
	private LinearLayout	              leftMenuLi;
	private final ShipMentWelcomeActivity	theAc	= ShipMentWelcomeActivity.this;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.shipment_welcome_main);
		// 提交表单成功后，初始化所属列表任务，若无任务此处不提醒
		// 接收服务器信息进行版本更新
		update = new UpdateBiz();
		update.getVersionInfo(handlers, this);
		// 获取所有app版本
		Tools tools = new Tools();
		data = tools.listPackages(this);
		Log.i("TTT", data.toString());
		initView();
		String massege = getIntent().hasExtra("initResultMsg") == false ? "" : getIntent()
		        .getStringExtra("initResultMsg");

		if(massege.length() > 0) {
			Toast.makeText(theAc, massege, Toast.LENGTH_SHORT).show();
		}
	}

	private void initView() {
		idTitleLeftBtn = (ImageButton) findViewById(R.id.id_title_left_btn);
		leftMenuLi = (LinearLayout) findViewById(R.id.left_menu);
		idTitleLeftBtn.setOnClickListener(theClickAction);
		View idFragmentContent = findViewById(R.id.id_fragment_content);
		// 触碰到该区域默认左菜单消失
		idFragmentContent.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View arg0,MotionEvent arg1) {
				leftMenuLi.setVisibility(View.GONE);
				return false;
			}
		});
	}

	private final OnClickListener	theClickAction	= new OnClickListener() {

		                                               @Override
		                                               public void onClick(View arg0) {
			                                               switch (arg0.getId()) {
															   case R.id.id_title_left_btn:
																   // 根据菜单的显隐情况切换状态
																   if(leftMenuLi.isShown()) {
																	   leftMenuLi
																	           .setVisibility(View.GONE);
																   } else {
																	   leftMenuLi
																	           .setVisibility(View.VISIBLE);
																   }
																   break;

															   default:
																   break;
														   }
													   }
	                                               };

	// 在需要监听的activity中重写onKeyDown()。返回键
	@Override
	public boolean onKeyDown(int keyCode,KeyEvent event) {

		if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			startActivity(new Intent(theAc, MainActivity.class));
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 调用升级action
	 * UpdataAppAction
	 */

	private UpdateBiz	              update;
	public ProgressBar	              mProgress;
	public AlertDialog	              downloadDialog;
	private boolean	                  flag	   = true;
	private boolean	                  judge	   = false;
	private List<Map<String, Object>>	data;
	private final List<Integer>	      count	   = new ArrayList<Integer>();
	private final List<Integer>	      apkcount	= new ArrayList<Integer>();
	public Handler	                  handlers	= new Handler() {
		                                           @Override
		                                           public void handleMessage(android.os.Message msg) {
			                                           try {
				                                           int msgId = msg.what;
				                                           Bundle bundle = msg.getData();
				                                           if(msgId == HttpConstant.GET_VERSION_SUCCEE) {
					                                           VersionEntity versionEntity = (VersionEntity) bundle
					                                                   .getSerializable(HttpConstant.KEY_VERSION_DATA);
					                                           downVersion(versionEntity);
				                                           } else if(msgId == HttpConstant.GET_VERSION_FAIL) {
					                                           return;
				                                           }
				                                           if(msgId == HttpConstant.DOWN_APK_SUCCEE) {
					                                           String apkPath = bundle
					                                                   .getString(HttpConstant.KEY_DATA);
					                                           Tools.installApk(apkPath, theAc);
				                                           }
			                                           } catch (Exception e) {}
		                                           }
	                                           };

	private void showVersion(final List<Integer> c,final String[] path,final String[] apkUrl,
	        final VersionEntity versionEntity) throws NameNotFoundException {
		if(judge) {
			long[] size = versionEntity.getFileLength();
			long sumSize = 0;
			for(int j = 0;j < count.size();j++) {
				int i = count.get(j);
				sumSize += size[i];
			}
			double bs = sumSize / 1024 / 1024;
			AlertDialog.Builder dialog = new Builder(theAc);
			dialog.setMessage(versionEntity.getChangeLog());
			if(bs == 0) {
				dialog.setTitle("版本更新！");
			} else {
				dialog.setTitle("更新总耗流量：" + bs + "M");
			}
			dialog.setPositiveButton("升级", new AlertDialog.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog,int which) {
					for(int i = 0;i < c.size();i++) {
						setDownApk(c.get(i), path, apkUrl, versionEntity);
					}
					dialog.cancel();
				}
			});
			dialog.setNegativeButton("取消", new AlertDialog.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog,int which) {
					dialog.cancel();
				}
			});
			dialog.show();
		}
	}

	/**
	 * 客户手机版本
	 * @param versionEntity
	 */
	protected void downVersion(VersionEntity versionEntity) {
		String[] apkUrl = versionEntity.getApkUrl();
		String fileName = "";
		String[] path = new String[apkUrl.length];
		for(int j = 0;j < apkUrl.length;j++) {
			try {
				Map<String, Object> app = null;
				double[] version = null;
				double versionCode = 0;
				if(j < data.size()) {
					app = data.get(j);
					version = versionEntity.getNewVersion();
					Object versionCodeString = app.get("versionCode");
					versionCode = (Double) versionCodeString;
					for(int i = 0;i < apkUrl.length;i++) {
						int index = apkUrl[i].lastIndexOf("/");
						fileName = apkUrl[i].substring(index + 1);
						path[i] = HttpConstant.APK_PATH + "/" + fileName;
						if(app.containsKey("船家宝") && fileName.equals("ChuanJiaBao_mobile.apk")
						        && version[i] > versionCode) {
							judge = true;
							count.add(i);
						} else if(app.containsKey("船家宝")
						        && fileName.equals("ChuanJiaBao_mobile.apk")) {
							apkcount.add(i);
						}
					}
				} else if(j <= data.size()) {
					int sum = apkcount.size();
					boolean flags = true;
					int n = 0;
					for(n = 0;n < apkUrl.length;n++) {
						for(int i = 0;i < sum;i++) {
							if(n == apkcount.get(i)) {
								flags = false;
							}
						}
						if(flags) {
							count.add(n);
							judge = true;
						}
						flags = true;
					}
					break;
				}
			} catch (Exception e) {}
		}
		if(judge) {
			try {
				showVersion(count, path, apkUrl, versionEntity);
			} catch (NameNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} else {
			// 删除下载文件的存放文件夹
			File filePath = new File(HttpConstant.APK_PATH);
			deleteFile(filePath);
		}
	}

	public void deleteFile(File file) {
		if(file.exists()) { // 判断文件是否存在
			if(file.isFile()) { // 判断是否是文件
				file.delete(); // delete()方法 你应该知道 是删除的意思;
			} else if(file.isDirectory()) { // 否则如果它是一个目录
				File files[] = file.listFiles(); // 声明目录下所有的文件 files[];
				for(int i = 0;i < files.length;i++) { // 遍历目录下所有的文件
					this.deleteFile(files[i]); // 把每个文件 用这个方法进行迭代
				}
			}
			file.delete();
		}
	}

	private void setDownApk(int i,String[] path,String[] apkUrl,VersionEntity versionEntity) {
		// TODO Auto-generated method stub
		try {
			File files = null;
			File file = new File(path[i]);
			long length = file.length();
			long[] fileLength = versionEntity.getFileLength();
			if(file.exists() && length == fileLength[i]) {
				Tools.installApk(path[i], theAc);
			} else {
				String sdcardState = Environment.getExternalStorageState();
				if(Environment.MEDIA_MOUNTED.equals(sdcardState)) {
					// 有sdcard
					// 判断path有没有
					File filePath = new File(HttpConstant.APK_PATH);
					if(!filePath.exists()) {
						filePath.mkdirs();
					}
					// 判断file有没有
					files = new File(path[i]);
					if(files.exists()) {
						files.delete();
					}
					boolean flag = NetworkUtil.checkNetworkState(theAc);
					if(flag) {
						UpdateBiz updateBiz = new UpdateBiz();
						updateBiz.downloadApk(handlers, path[i], apkUrl[i], theAc, files);
					} else {
						isDownDialog(path[i], apkUrl[i], files);
					}
				}
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	protected void isDownDialog(final String path,final String apkUrl,final File files) {
		// TODO Auto-generated method stub
		if(flag) {
			flag = false;
			AlertDialog.Builder downdialog = new Builder(theAc);
			downdialog.setTitle("现在不是wifi网络，你是否继续下载");
			downdialog
			        .setPositiveButton("是", new android.content.DialogInterface.OnClickListener() {
				        @Override
				        public void onClick(DialogInterface dialog,int which) {
					        UpdateBiz updateBiz = new UpdateBiz();
					        updateBiz.downloadApk(handlers, path, apkUrl, theAc, files);
				        }
			        });
			downdialog
			        .setNegativeButton("否", new android.content.DialogInterface.OnClickListener() {
				        @Override
				        public void onClick(DialogInterface dialog,int which) {
					        dialog.cancel();
				        }
			        });
			downdialog.show();
		}
	}

}
